<?php
namespace app\middleware;

use app\common\service\JwtService;
use think\facade\Request;
use think\facade\Response;

class ApiAuth
{
    public function handle($request, \Closure $next)
    {
        $token = $request->header('Authorization');

        if (!$token || !preg_match('/^Bearer\s+(.+)$/', $token, $matches)) {
            return Response::json([
                'code' => 401,
                'msg' => '未提供Token或格式错误'
            ], 401);
        }

        $jwtService = new JwtService();
        $payload = $jwtService->verifyToken($matches[1]);

        if (!$payload) {
            return Response::json([
                'code' => 401,
                'msg' => 'Token无效或已过期'
            ], 401);
        }

        // 将用户ID绑定到请求对象
        $request->uid = (int)$payload['uid'];

        return $next($request);
    }
}